<template>
  <view v-if="currentIndex>-1">
    <!-- 占位元素 -->
    <view class="dp-tabbar-bot"></view>
    
    <!-- tabbar主体 -->
    <view class="dp-tabbar-bar" :style="{backgroundColor: menudata.backgroundColor}">
      <view 
        v-for="(item, index) in menudata.list" 
        :key="index"
        class="dp-tabbar-item"
        @click="goto(index, item.pagePath)"
      >
        <view class="dp-tabbar-image-box">
          <image 
            class="dp-tabbar-icon"
            :src="currentIndex === index ? item.selectedIconPath : item.iconPath"
          />
        </view>
        <view class="dp-tabbar-text" :style="{color: currentIndex === index ? menudata.selectedColor : menudata.color}">
          {{item.text}}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'CustomTabbar',
  data() {
    return {
      currentIndex: 0,
      menudata: {
        backgroundColor: '#ffffff',
        color: '#999999',
        selectedColor: '#0086EF',
        list: [
          {
            pagePath: '/pages/agent/index',
            text: '设备',
            iconPath: '/static/img/agent/index.png',
            selectedIconPath: '/static/img/agent/index_a.png'
          },
          {
            pagePath: '/pages/agent/usercenter',
            text: '我的',
            iconPath: '/static/img/agent/mine.png',
            selectedIconPath: '/static/img/agent/mine_a.png'
          }
        ]
      }
    }
  },
  
  mounted() {
    this.initCurrentTab()
  },
  
  methods: {
    initCurrentTab() {
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      const currentPath = '/' + currentPage.route
      
      // 匹配当前路径
      this.menudata.list.forEach((item, index) => {
        if(currentPath === item.pagePath) {
          this.currentIndex = index
        }
      })
    },
    
    goto(index, url) {
      if(this.currentIndex === index) return
      
      this.currentIndex = index
      
      // 使用 redirectTo 替代 navigateTo,避免页面堆栈问题
      uni.redirectTo({
        url,
        success: () => {
          // 成功跳转后更新当前索引
          this.currentIndex = index
        }
      })
    }
  }
}
</script>

<style>
.dp-tabbar-bot {
  height: 110rpx;
  width: 100%;
  box-sizing: content-box;
}

.dp-tabbar-bar {
  position: fixed;
  display: flex;
  align-items: center;
  flex-direction: row;
  width: 100%;
  height: 110rpx;
  bottom: 0;
  background: #fff;
  z-index: 999;
}

.dp-tabbar-item {
  flex: 1;
  text-align: center;
  overflow: hidden;
}

.dp-tabbar-image-box {
  height: 54rpx;
  margin-bottom: 4rpx;
}

.dp-tabbar-icon {
  width: 50rpx;
  height: 50rpx;
}

.dp-tabbar-text {
  line-height: 30rpx;
  font-size: 24rpx;
}
/* @supports(padding-bottom: env(safe-area-inset-bottom)) {
  .dp-tabbar-bot {
    padding-bottom: env(safe-area-inset-bottom);
  }
  .dp-tabbar-bar {
    padding-bottom: env(safe-area-inset-bottom);
  }
} */
</style>